<?php
/**
 * Created by PhpStorm.
 * User: xy01
 * Date: 2021/8/18
 * Time: 15:56
 *  日志消息队列
 */

namespace App\Amqp;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use App\Service\LogQueue;

class Log
{

    public $queue_name; //队列名称
    public $exec_name;  //交换器名称
    public $k_route;    //绑定名称

    public $connection; //连接
    public $channel;  //通道


    public function __construct($config,$queue_name='',$exec_name='',$k_route='')
    {
        $this->queue_name = $queue_name;
        $this->exec_name = $exec_name;
        $this->k_route = $k_route;

        $this->connection = new AMQPStreamConnection($config['host'], $config['port'], $config['username'], $config['password'],$config['ku']);
        //创建通道
        $this->channel = $this->connection->channel();
    }

     /*
     * 消费者
     */
    public function receive(){



        $this->channel->queue_declare( $this->queue_name , false , true, false , false);  //第三个参数true开启持久化

        $callback=function($msg){


//           LogQueue::logInsert($msg->body);
//           $msg->ack();
        };

        $this->channel->basic_qos(null,1,null);    //开启持久化 需要ack确认消费
        $this->channel->basic_consume($this->queue_name,'', false , false , false , false , $callback); //第三个参数true不需要确认消费

        while( $this->channel->is_open()){
            $this->channel->wait();
        }

        $this->channel->close();
        $this->connection->close();
    }

    /*
     * 生产者
     * $msg 发布内容
     */
    public function production($content){

        $this->channel->queue_declare($this->queue_name, false, true, false, false);   //声明队列   第三个参数true开启持久话
        $msg= new AMQPMessage($content,array('delivery_mode' =>    AMQPMessage::DELIVERY_MODE_PERSISTENT));    //消息标记为持久性

        $this->channel->basic_publish($msg,'',$this->queue_name);

        $this->channel->close();
        $this->connection->close();
    }



}